package com.nassir.chatroom.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.nassir.chatroom.constant.Constant;
import com.nassir.chatroom.model.ClientModel;
import com.nassir.chatroom.thread.ServerThread;
import com.nassir.chatroom.util.ClientManager;
import com.nassir.chatroom.util.DynamicConfig;
import com.nassir.chatroom.util.Logs;

/**
 * 聊天服务器
 * 
 * @author nassir.wen
 * @date 2012-12-3下午5:39:28
 * @Copyright: Copyright (c) 2012
 */
public class TalkServer {
	private int clientNum = 1;

	public TalkServer() {
	    startSeverService();
	}

	private void startSeverService() {
		ServerSocket serverSocket = null;
		boolean listening = true;
		try {
			int port = DynamicConfig.getInstance().getInt(Constant.SERVER_PORT);
			Logs.info("服务器启动端口" + port + "服务");
			serverSocket = new ServerSocket(port);
		} catch (IOException e) {
		}
		Logs.info("服务器启动成功");
		while (listening) {
			try {
				Socket client = serverSocket.accept();
				new ServerThread(client, clientNum).start();
				ClientModel clientModel = new ClientModel();
				clientModel.setClientId(clientNum);
				clientModel.setClientName("[游客" + clientNum + "]");
				clientModel.setClient(client);
				ClientManager.getInstance().add(clientModel);
				Logs.info("客户端: " + clientModel.getClientName() + "连接成功");
				Thread.sleep(1 * 1000);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			// 监听到客户请求，根据得到的Socket对象和客户计数创建服务线程，并启动之
			clientNum++; // 增加客户计数
		}
		try {
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
